package com.hzit.service.impl;

import com.github.pagehelper.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzit.common.utils.PageResult;
import com.hzit.entity.Classes;
import com.hzit.entity.Student;
import com.hzit.mapper.ClassesMapper;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.StudentService;
import com.hzit.util.MySqlSessionFactory;
import com.hzit.vo.StudentVO;
import org.apache.ibatis.session.SqlSession;


import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
public class StudentServiceImpl implements StudentService {

	/**
	 * 1. 查询所有学生
	 * @return
	 * @throws IOException
	 */
	@Override
	public List<Student> findAll() throws IOException {
		try (SqlSession session = MySqlSessionFactory.getSqlSession(true)) {
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			return mapper.findAll();
		}
	}

	/**
	 * 2. 分页查询
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@Override
	public PageResult<Student> findByPage(Integer page, Integer pageSize) throws IOException {
		// 2.1 开始分页
		PageHelper.startPage(page,pageSize);
		// 2.2 开始查询
		List<Student> students = this.findAll();
		// 2.3 将上面的集合转换为Page对象
		Page<Student> studentPage = (Page<Student>) students;
		long total = studentPage.getTotal();
		List<Student> result = studentPage.getResult();
		return new PageResult<>(total,result);
	}

	/**
	 * 3. 条件查询带分页
	 * @param page
	 * @param pageSize
	 * @param studentVO
	 * @return
	 */
	@Override
	public PageResult<Student> search(Integer page, Integer pageSize, StudentVO studentVO) throws IOException {
		// 3.1 开始分页
		PageHelper.startPage(page,pageSize);
		// 3.2 开始查询
		try(SqlSession session = MySqlSessionFactory.getSqlSession(true)){
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			ClassesMapper classesMapper = session.getMapper(ClassesMapper.class);
			List<Student> students = mapper.search(studentVO);
			// 3.3 为student对象设置cname属性
			for (Student student : students) {
				Classes classes = classesMapper.findById(student.getCid());
				student.setCname(classes.getCname());
			}
			// 3.4 转换为IPage对象
			Page<Student> studentPage = (Page<Student>) students;
			return new PageResult<>(studentPage.getTotal(),studentPage.getResult());
		}
	}
}
